import { ref, computed } from 'vue'
import { marked } from 'marked'
import Prism from 'prismjs'

// 动态导入Prism.js主题和插件
const loadPrismTheme = async () => {
  const theme = localStorage.getItem('theme') || 'light'
  if (theme === 'dark') {
    await import('prismjs/themes/prism-tomorrow.min.css')
  } else {
    await import('prismjs/themes/prism.min.css')
  }
}

// 按需加载Prism插件
const loadPrismPlugins = async () => {
  const plugins = [
    'prismjs/plugins/line-numbers/prism-line-numbers.min.css',
    'prismjs/plugins/line-numbers/prism-line-numbers.min.js',
    'prismjs/plugins/autoloader/prism-autoloader.min.js',
    'prismjs/plugins/normalize-whitespace/prism-normalize-whitespace.min.js',
    'prismjs/plugins/autolinker/prism-autolinker.min.css',
    'prismjs/plugins/autolinker/prism-autolinker.min.js'
  ]
  
  return Promise.all(plugins.map(plugin => import(plugin)))
}

// 按需加载语言支持
const loadLanguages = async (languages = ['java', 'css', 'javascript', 'python']) => {
  const imports = languages.map(lang => import(`prismjs/components/prism-${lang}`))
  return Promise.all(imports)
}

export function useMarkdown() {
  const markdownContent = ref('')
  const isLoading = ref(false)
  const error = ref(null)
  
  // 提取标题
  const extractHeadings = (md) => {
    const lines = md.split('\n')
    const headings = []
    
    lines.forEach((line, idx) => {
      const match = /^(#{2,6})\s+(.+)/.exec(line)
      if (match) {
        const level = match[1].length
        const text = match[2].trim()
        const id = `heading-${idx}-${text.replace(/\s+/g, '-').replace(/[^\w-]/g, '')}`
        headings.push({ text, level, id })
      }
    })
    
    return headings
  }
  
  // 自定义渲染器
  const createRenderer = (headings) => {
    const renderer = new marked.Renderer()
    
    // 自定义代码块渲染
    renderer.code = (code, language) => {
      const lang = language && Prism.languages[language] ? language : 'clike'
      const highlighted = Prism.highlight(code, Prism.languages[lang], lang)
      
      return `
        <div class="code-block-container" data-language="${lang}">
          <div class="code-header">
            <span class="language-tag">${lang}</span>
            <div class="code-actions">
              <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(code)}" title="复制代码">
                <i class="fas fa-copy"></i>
                <span>复制</span>
              </button>
              ${lang === 'html' ? `
                <button class="code-action-btn run-btn" data-code="${encodeURIComponent(code)}" title="运行代码">
                  <i class="fas fa-play"></i>
                  <span>运行</span>
                </button>
              ` : ''}
            </div>
          </div>
          <pre class="line-numbers"><code class="language-${lang}">${highlighted}</code></pre>
        </div>
      `
    }
    
    // 自定义标题渲染
    renderer.heading = (text, level) => {
      if (level >= 2 && level <= 6) {
        const heading = headings.find(h => h.text === text && h.level === level)
        const id = heading ? heading.id : text.replace(/\s+/g, '-').replace(/[^\w-]/g, '')
        return `<h${level} id="${id}" class="heading-anchor">${text}</h${level}>`
      }
      return `<h${level}>${text}</h${level}>`
    }
    
    return renderer
  }
  
  // 编译markdown
  const compiledMarkdown = computed(() => {
    if (!markdownContent.value) return ''
    
    const headings = extractHeadings(markdownContent.value)
    const renderer = createRenderer(headings)
    
    marked.setOptions({
      renderer,
      highlight: function(code, lang) {
        if (lang && Prism.languages[lang]) {
          return Prism.highlight(code, Prism.languages[lang], lang)
        }
        return code
      },
      breaks: true,
      gfm: true
    })
    
    return marked(markdownContent.value)
  })
  
  // 加载markdown文件
  const loadMarkdown = async (filepath) => {
    isLoading.value = true
    error.value = null
    
    try {
      // 初始化Prism
      await Promise.all([
        loadPrismTheme(),
        loadPrismPlugins(),
        loadLanguages()
      ])
      
      // 加载markdown内容
      const response = await fetch(filepath)
      if (!response.ok) {
        throw new Error(`Failed to load markdown: ${response.statusText}`)
      }
      
      const content = await response.text()
      markdownContent.value = content
      
      return content
    } catch (err) {
      error.value = err.message
      console.error('Error loading markdown:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  return {
    markdownContent,
    compiledMarkdown,
    isLoading,
    error,
    loadMarkdown,
    extractHeadings
  }
} 